package com.example.service.impl;

import com.example.mapper.AddressMapper;
import com.example.pojo.Address;
import com.example.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AddressMapper addressMapper;

    @Override
    public List<Address> getAddressTree() {
        // 获取顶级地址
        List<Address> topLevel = addressMapper.selectTopLevel();
        // 递归设置子地址
        for (Address address : topLevel) {
            setChildren(address);
        }
        return topLevel;
    }

    // 递归查询子地址
    private void setChildren(Address parent) {
        List<Address> children = addressMapper.selectByParentId(parent.getValue());
        if (!children.isEmpty()) {
            parent.setChildren(children);
            for (Address child : children) {
                setChildren(child); // 递归处理子地址
            }
        }
    }
}